package com.example.united.jms.subscriber;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;

/**
 * User: AGrankin
 * Date: 09.04.14
 * Time: 11:13
 */
public class JMSSubscriber implements MessageListener {

    private TopicConnectionFactory topicConnectionFactory;
    private TopicConnection topicConnection;
    private TopicSession topicSession;
    private TopicSubscriber topicSubscriber;
    private Topic topic;

    private static InitialContext getInitialContext() throws NamingException {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://10.249.140.252:7005");
        env.put("weblogic.jndi.createIntermediateContexts", "true");
        return new InitialContext(env);
    }

    public void init(Context ctx, String topicName) throws NamingException, JMSException {
        topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("crdsPartyTopicConnectionFactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = (Topic)ctx.lookup(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);
        topicSubscriber.setMessageListener(this);
        topicConnection.start();
    }

    @Override
    public void onMessage(Message message) {
        try {
            String msgText;
            if (message instanceof TextMessage) {
                msgText = ((TextMessage)message).getText();
            } else {
                msgText = message.toString();
            }
            System.out.println("JMS Message Received: " + msgText);
        } catch (JMSException e) {
            System.err.println("An exception occurred: " + e.getMessage());
        }
    }

    public void close() throws JMSException {
        topicSubscriber.close();
        topicSession.close();
        topicConnection.close();
    }

    public static void main (String... args) throws Exception {
//        InitialContext initialContext = getInitialContext();
//        JMSSubscriber jmsSubscriber = new JMSSubscriber();
//        jmsSubscriber.init(initialContext, "crdsPartyTopic");
//        jmsSubscriber.close();
    }
}
